package eu.web.permission;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import eu.jk.config.ConfigEngine;

/**
 * 权限验证器
 * 
 * @author WZZ
 * 
 */
public class PermissionValidater {

	private Map<String, Access> map = new HashMap<String, Access>();

	/**
	 * 获取权限验证器
	 * 
	 * @return
	 */
	public static PermissionValidater getValidater(String path, String encoding) {
		PermissionValidater validater = new PermissionValidater();
		ConfigEngine engine = ConfigEngine
				.getEngine(ConfigEngine.EngineType.XMLEngine);
		engine.init(path, encoding);
		engine.locate("/permission/rules");
		for (String vpath : engine.getValues("rule/path")) {
			String power = engine.getValue("rule[path='" + vpath + "']/power");
			validater.map.put(vpath, new Access(vpath, power));
		}
		return validater;
	}

	/**
	 * 验证是否符合权限
	 * 
	 * @param url
	 * @param powers
	 * @return
	 */
	public boolean validate(String url, Collection<String> powers) {
		Set<String> powerSet = null;
		if (powers != null && !powers.isEmpty()) {
			if (!(powers instanceof Set)) {
				powerSet = new HashSet<String>();
				for (String power : powers)
					powerSet.add(power);
			} else {
				powerSet = (Set<String>) powers;
			}
		}

		while (url != null) {
			if (map.containsKey(url)) {
				return map.get(url).validate(powerSet);
			}
			url = UpUrl(url);
		}
		return false;
	}

	/**
	 * 验证是否符合权限
	 * 
	 * @param url
	 * @param power
	 * @return
	 */
	public boolean validate(String url, String power) {
		Set<String> powers = new HashSet<String>();
		powers.add(power);
		return validate(url, powers);
	}
	
	private String UpUrl(String url) {
		if (url.contains("/")) {
			if ("/".equals(url))
				return null;
			String t = url.substring(0, url.lastIndexOf("/"));
			if (t.length() == 0)
				return "/";
			return t;
		}
		return null;
	}

	private PermissionValidater() {
	}

}
